package com.iot.ammeter

import android.app.Application
import android.content.pm.ApplicationInfo
import android.util.Log
import androidx.room.Room
import androidx.room.RoomDatabase
import com.iot.ammeter.model.parcelable.DeviceInfo
import com.iot.ammeter.model.parcelable.LastMonthInfo
import com.iot.ammeter.model.parcelable.UserInfo
import com.iot.ammeter.storage.*
import com.tencent.mmkv.MMKV

const val DATABASE_NAME = "Ammeter.db"

class IApplication : Application() {

    companion object {
        var token: String? = null
            set(value) {
                writeUserToken(value)
                field = value
            }

        var userInfo: UserInfo? = UserInfo("", null, 0F, false)
            set(value) {
                writeUserInfoLocally(value)
                field = value
            }
        var deviceInfo: DeviceInfo? = null
            set(value) {
                writeDeviceInfoLocally(value)
                field = value
            }

        var lastMonthInfo: LastMonthInfo? = null
            set(value) {
                writeLastMonthInfoLocally(value)
                field = value
            }

        // 全局访问上下文对象
        lateinit var context: Application

        // RoomDatabase 单例
        lateinit var db: AmmeterDatabase

        // 是否为 debug 环境
        val isDebugEnv: Boolean get() = context.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0

    }

    override fun onCreate() {
        super.onCreate()
        // 初始化 MMKV
        MMKV.initialize(this)
        context = this
        db = Room.databaseBuilder(this, AmmeterDatabase::class.java, DATABASE_NAME).build()
        Log.d("环境检测：", "=> debug=$isDebugEnv")
    }
}
